package com.gulimall.auth.service.impl;

import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import com.gulimall.auth.feign.SmsFeignService;
import com.gulimall.auth.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @Author lhj
 * @Date 2024/3/2 10:40
 */
@Slf4j
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    SmsFeignService smsFeignService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    /**
     * 发送短信功能
     * @param phone 手机号
     * @return
     */
    @Override
    public R sendCode(String phone) {
        try {
            log.info("LoginServiceImpl.sendCode com in receive parameter: {}", phone);
            if (StringUtils.isEmpty(phone)) {
                return R.error("手机号不能为空");
            }

            // 手机号校验规则
            String regex = "^1[3-9]\\d{9}$";
            if (!phone.matches(regex)) {
                return R.error("手机号格式不正确");
            }
            String redisKey = (AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
            String cacheCode = stringRedisTemplate.opsForValue().get(redisKey);
            if (!StringUtils.isEmpty(cacheCode)) {
                long cacheTime = Long.parseLong(cacheCode.split("_")[1]);
                long currentTimeMillis = System.currentTimeMillis();
                if (currentTimeMillis - cacheTime < 60000) {
                    return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
                }
            }

            String code = getCode(6);
            log.info("LoginService.sendCode 验证码为：{}", code);
            R sendResult = smsFeignService.sendSmsCode(phone, code);
            if (sendResult.getCode() != 0) {
                return sendResult;
            }
            stringRedisTemplate.opsForValue().set(redisKey, code + "_" + System.currentTimeMillis(), 10, TimeUnit.MINUTES);
            return R.ok();
        } catch (NumberFormatException e) {
            log.error("短信发送异常，error: {}", e);
            return R.error("短信发送失败，请重试");
        }
    }


    /**
     * 生成随机码
     * @param length 随机码的长度
     * @return
     */
    private static String getCode(int length) {
        StringBuilder builder = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            builder.append(random.nextInt(10));
        }
        String code = builder.toString();
        return code;
    }


}
